<template>
  <div class="settings-container">
    <h2>账号设置</h2>

    <el-tabs v-model="activeTab" class="settings-tabs">
      <el-tab-pane label="个人资料" name="profile">
        <el-form ref="profileFormRef" :model="profileForm" :rules="profileRules" label-width="100px" class="profile-form">
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              action="/api/user/avatar" 
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders"
              name="avatar" 
            >
              <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" alt="用户头像"/>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <div class="el-upload__tip">
                点击上传头像，仅支持 JPG/PNG 格式，大小不超过 2MB
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="profileForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="个人简介" prop="bio">
            <el-input
              v-model="profileForm.bio"
              type="textarea"
              :rows="3"
              placeholder="介绍一下自己吧"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitProfileForm" :loading="loadingProfile">保存修改</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="修改密码" name="password">
        <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px" class="password-form">
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input type="password" v-model="passwordForm.currentPassword" placeholder="请输入当前密码" show-password></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" v-model="passwordForm.newPassword" placeholder="请输入新密码" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input type="password" v-model="passwordForm.confirmPassword" placeholder="请再次输入新密码" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitPasswordForm" :loading="loadingPassword">确认修改</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useStore } from 'vuex';
import axios from '@/services/axios';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const store = useStore();
const activeTab = ref('profile');
const loadingProfile = ref(false);
const loadingPassword = ref(false);

// --- 个人资料 --- 
const profileFormRef = ref(null);
const profileForm = reactive({
  username: '',
  avatar: '',
  bio: '',
});

const profileRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  bio: [
    { max: 200, message: '个人简介不能超过 200 个字符', trigger: 'blur' },
  ],
});

// 从 Vuex 获取用户信息
const currentUser = computed(() => store.state.user.currentUser);

// 上传请求头，携带 token
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${localStorage.getItem('token')}`,
}));

// 获取用户资料
const fetchUserProfile = async () => {
  if (currentUser.value) {
    profileForm.username = currentUser.value.username;
    profileForm.avatar = currentUser.value.avatar;
    profileForm.bio = currentUser.value.bio;
  } else {
    // 如果 Vuex 没有，尝试从 API 获取
    try {
      const response = await axios.get('/api/auth/me');
      const user = response.data.user;
      if (user) {
        profileForm.username = user.username;
        profileForm.avatar = user.avatar;
        profileForm.bio = user.bio;
        // 更新 Vuex store
        store.commit('user/setUser', user);
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      ElMessage.error('获取用户信息失败，请稍后重试');
    }
  }
};

// 头像上传成功处理
const handleAvatarSuccess = (response, uploadFile) => {
  // el-upload 的 on-success 直接接收后端返回的 JSON 数据体
  console.log('头像上传响应:', response); // 添加日志，确认 response 结构

  // 检查后端返回的 success 标志和 avatarUrl
  if (response && response.success === true && response.avatarUrl) {
    const avatarUrl = response.avatarUrl;
    profileForm.avatar = avatarUrl; // 更新显示的头像
    // 尝试从 auth 模块更新头像
    try {
      store.commit('auth/SET_USER', { ...store.state.auth.user, avatar: avatarUrl });
      console.log('Vuex auth/user avatar updated.');
    } catch (e) {
      console.warn('Failed to update avatar in auth module, trying user module:', e);
      // 兼容旧代码
      try {
        store.commit('user/updateUserAvatar', avatarUrl);
        console.log('Vuex user/currentUser avatar updated.');
      } catch (e2) {
        console.error('Failed to update avatar in both auth and user modules:', e2);
      }
    }
    ElMessage.success('头像上传成功!');
  } else {
    // 处理失败情况
    console.error('头像上传失败，响应数据格式不正确或 success 不为 true:', response);
    ElMessage.error(response?.message || '头像上传失败，请检查响应或联系管理员');
  }
};

// 头像上传前检查
const beforeAvatarUpload = (rawFile) => {
  const isJPG = rawFile.type === 'image/jpeg';
  const isPNG = rawFile.type === 'image/png';
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 提交个人资料修改
const submitProfileForm = async () => {
  if (!profileFormRef.value) return;
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      loadingProfile.value = true;
      try {
        const payload = {
          username: profileForm.username,
          bio: profileForm.bio,
        };
        // 使用 PUT 请求更新资料，与后端API路由匹配
        const response = await axios.put('/api/user/profile', payload);

        // 请求成功 (HTTP 2xx)
        ElMessage.success('个人资料更新成功!');

        // 更新 Vuex store (优先更新 auth 模块)
        const updatedUserData = { 
          ...store.state.auth.user, // 获取当前用户信息
          username: profileForm.username, 
          bio: profileForm.bio 
        };
        try {
          store.commit('auth/SET_USER', updatedUserData);
          console.log('Vuex auth/user profile updated.');
        } catch (e) {
          console.warn('Failed to update profile in auth module, trying user module:', e);
           // 兼容旧代码，尝试 user 模块
          try {
             store.commit('user/updateUserProfile', { 
               username: profileForm.username, 
               bio: profileForm.bio 
             });
             console.log('Vuex user/currentUser profile updated.');
          } catch (e2) {
             console.error('Failed to update profile in both auth and user modules:', e2);
          }
        }

      } catch (error) { 
        // 请求失败 (非 2xx 状态码)
        console.error('更新个人资料失败:', error);
        ElMessage.error(error.response?.data?.message || '更新个人资料失败，请稍后重试');
      } finally {
        loadingProfile.value = false;
      }
    }
  });
};

// --- 修改密码 --- 
const passwordFormRef = ref(null);
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
});

// 自定义确认密码验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'));
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的新密码不一致!'));
  } else {
    callback();
  }
};

const passwordRules = reactive({
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' },
  ],
});

// 提交密码修改
const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return;
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      loadingPassword.value = true;
      try {
        // 调用修改密码接口
        await axios.put('/api/user/password', { 
          currentPassword: passwordForm.currentPassword,
          newPassword: passwordForm.newPassword,
        });
        
        // 请求成功 (HTTP 2xx)
        ElMessage.success('密码修改成功!');
        passwordFormRef.value.resetFields(); // 清空表单

      } catch (error) {
        // 请求失败 (非 2xx 状态码)
        console.error('修改密码失败:', error);
        ElMessage.error(error.response?.data?.message || '修改密码失败，请稍后重试');
      } finally {
        loadingPassword.value = false;
      }
    }
  });
};

// 组件挂载时获取用户数据
onMounted(() => {
  fetchUserProfile();
});

</script>

<style scoped>
.settings-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  text-align: center;
  font-size: 24px;
  color: #303133;
}

.settings-tabs {
  margin-top: 20px;
}

.profile-form,
.password-form {
  margin-top: 20px;
  padding: 0 20px;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}

.el-upload__tip {
  font-size: 12px;
  color: #999;
  margin-top: 7px;
}
</style>